package ui.listeners;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import ui.CheckerBoardCanvas;
import ui.systems.BoardMoveControl;
import ui.systems.MoveAction;
import ui.systems.MoveActionData;

/**
 * Canvas listener that translates mouse clicks into changes on the GUI.
 * 
 * @author Team Titanium
 */
public class CheckerBoardCanvasMouseListener implements MouseListener {
	private int[] oldpos; // position where piece was moved from.
	private int oldpiece; // piece being moved.
	private int state;

	public CheckerBoardCanvasMouseListener() {
		state = GameMoveStates.NOOP;
		oldpos = new int[2];

	}

	public void mouseClicked(MouseEvent e) {
		

	}

	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	public void mouseReleased(MouseEvent e) {
		CheckerBoardCanvas target = (CheckerBoardCanvas) e.getComponent();
		int sq_width = (int) Math.ceil(target.getWidth() / 8);
		int sq_height = (int) Math.ceil(target.getHeight() / 8);

		int x_box = e.getX() / sq_width;
		int y_box = e.getY() / sq_height;

		int piece = target.getPieceAt(x_box, y_box);

		//System.out.printf("over: %d down: %d team: %s\n", x_box, y_box, who);
		
		MoveActionData move = new MoveActionData(this.oldpos[1], this.oldpos[0], y_box, x_box);
		
		int temp_oldpiece = BoardMoveControl.pieceAt(y_box, x_box);
		
		// from nothing to picked up
		if (this.state == GameMoveStates.NOOP && temp_oldpiece != 0) {
			this.state = GameMoveStates.PIECE_PICKED_UP;
			this.oldpos[0] = x_box;
			this.oldpos[1] = y_box;
			oldpiece = temp_oldpiece;
		}
		// dropped
		else if (this.state == GameMoveStates.PIECE_PICKED_UP) {
			MoveAction f = new MoveAction(move);
			this.state = GameMoveStates.NOOP;
			// move only if valid.
			//if (BoardMoveControl.isValidMove(oldpiece, move)) {
			if (BoardMoveControl.movePiece(f)) {
				target.setBoard(BoardMoveControl.getBoard());
				target.repaint();
			}
			else {
				System.err.println("Move invalid");
			}
		}

	}

}

/**
 * Holds the states that a piece will go through in the course of game play. For
 * example, picked up or noop (which means it's sitting in place).
 * 
 * @author Team Titanium
 */
class GameMoveStates {
	public static final int NOOP = 0x00;
	public static final int PIECE_PICKED_UP = 0x0f;
}
